<template>
  <div class="searchHead">
    <div class="tools">
      <el-row :gutter="20">
        <!-- 订单时间 -->
        <span class="item" v-if="activeName === 'history'">
          <el-select v-model="formData.historyType"
          :placeholder="$t('order.inputChoose')"
          @change="handleSearchData"
          class="selectWidth"
          size="small"
          style="width: 185px;">
            <el-option
              v-for="item in historyTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              style="font-size: 12px;">
            </el-option>
          </el-select>
        </span>
        <!-- 币种 -->
        <span class="item">
          <span class="label">{{$t('quotation.symbol')}} </span>
          <el-popover
            placement="bottom"
            width="150"
            trigger="focus"
            :popper-class="handleClass"
            v-model="historyVisible">
            <ul class="historyList codeList" v-if="formData.coinCode">
              <li
                v-for="(item, index) in codeList"
                :key="index"
                @click="handleSelectCodeList(item, index)"
                style="font-size: 12px;">
                {{ item.symbolFormat }}
                <img
                  v-if="item.crossChain"
                  src="../../../static/img/chain/celian.png"
                  class="iconfont celianImg"/>
              </li>
            </ul>
            <ul class="historyList" v-else>
              <li
                v-for="(item, index) in historyList"
                :key="index"
                @click="handleSelectHistory(item, index)"
                style="font-size: 12px;">
                {{ item }}
              </li>
              <li v-if="historyList && historyList.length === 0" style="cursor: default;">
                <span style="opacity: 0.5; font-size: 12px;">{{ $t('public.noHistory') }}</span>
              </li>
            </ul>
            <!-- 交易对 -->
            <el-input
              :placeholder="$t('order.coinInput')"
              v-model="formData.coinCode"
              clearable
              style="width: 150px;"
              ref="historyInput"
              slot="reference"
              class="coinInput"
              @clear="handleInitSearch"
              @keyup.native="handleShowCodeList"
              size="small"
              >
            </el-input>
          </el-popover>
        </span>
        <!-- 币种类别 -->
        <!-- <span class="item coinType">
          <span class="label"> / </span>
          <el-select
            v-model="formData.valuationCoinCode"
            @change="handleSearchData"
            class="selectWidth"
            style="width: 90px;"
            size="small">
            <el-option v-for="item in coinType[$store.state.app.scatter.chain.toUpperCase()]" :key="item.value"
              :label="item.label || $t('order.all')"
              :value="item.value"
              style="font-size: 12px;">
            </el-option>
          </el-select>
        </span> -->
        <!-- 方向 -->
        <span class="item">
          <span class="label" style="margin-right: 15px;">{{$t('order.direction')}} </span>
          <el-select v-model="formData.direction"
          @change="handleSearchData"
          :placeholder="$t('order.inputChoose')" class="selectWidth"
          size="small"
          style="width: 80px;">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              style="font-size: 12px;">
            </el-option>
          </el-select>
        </span>
        <!-- 时间区间 -->
        <span class="item" v-if="formData.historyType || formData.historyType === 0">
          <span class="label" style="margin-right: 15px;">{{$t('order.time')}} </span>
          <timeVue @ListenTimeArr="ListenTimeArr" :resetData="resetData" :disData="formData.historyType" style="width:240px;"></timeVue>
        </span>
        <div style="display: inline-block;" v-if="$store.state.app.scatter.chain==='eos'">
          <span class="ml">{{$t('tronExchange.entrustmentInstruction')}}</span>
          <div style="display: inline-block;">
            <el-tooltip placement="top">
              <div slot="content" style="width: 270px; padding: 10px">
                  <p class="mb5">{{$t('tronExchange.entrustmentTip1', {amount: orderRows.amount})}}</p>
                  <p class="mb5">{{$t('tronExchange.entrustmentTip2')}}</p>
                  <p style="color: #999; text-indent: 5px; margin-top: 10px;">{{$t('tronExchange.entrustmentTip4')}}</p>
                </div>
                <div class="volatility">
                  <i class="iconfont icon-huaban"></i>
                </div>
            </el-tooltip>
          </div>
        </div>
        <!-- 导出 -->
        <span
          class="item export fr"
          v-if="activeName === 'history'"
          @click="handleExportOrder"
          :style="$store.state.app.language === 'ko' ? 'margin: 0;' : ''">
          <span>
            {{ $t('order.export') }}
            <i class="iconfont icon-daochu"></i>
          </span>
        </span>
        <!-- 隐藏已撤销 -->
        <span class="item ml10" v-if="activeName === 'history'">
          <el-checkbox
          @change="handleSearchData"
          v-model="formData.hidRevokeOrder">{{ $t('order.revokedHidden') }}</el-checkbox>
        </span>
      </el-row>
    </div>
  </div>
</template>

<script>
// import { EosModel } from '@/utils/eos';
import { getUrlParams, authorized } from '@/utils/validate';
import timeVue from '../../views/order/components/time'; // 时间控件

export default {
  name: 'searchHead', // 订单头部
  components: {
    timeVue
  },
  data() {
    return {
      formData: {},
      // 币种列表
      coinList: [],
      // 排序时间
      typeList: [],
      // 订单时间
      historyTypeList: [],
      // 方向列表
      coinType: {},
      // 成交状态
      statusTip: [],
      historyList: [], // 历史数据
      historyVisible: false,
      isClick: true, // 避免重复点击
      codeList: [], // 查询列表
      codeListData: [], // 币种列表
    }
  },
  props: {
    formDataget: {
      type: Object,
      default: null
    },
    activeName: {
      type: String,
      default: 'current',
    },
    hasDataForTable: {
      type: Number,
      default: 0,
    },
    resetData: {
      type: Number,
      default: 0,
    },
    orderRows: {}
  },
  watch: {
    '$store.state.app.language': function listen() {
      this.dataReset();
    },
    'formDataget.timerUpdate': function change() {
      this.formData = this.formDataget;
    },
    activeName: function change(val) {
      // 跳转到历史委托
      this.formData.historyType = 0;
      const href = window.location.href;
      const urlparams = getUrlParams(href);
      if (urlparams && urlparams.way === 'history') {
        this.formData.historyType = 2;
      }
      if (val === 'current') {
        this.formData.historyType = -1;
      }
    }
  },
  computed: {
    handleClass() {
      // return !this.historyList.length ? 'noIcon historyData' : 'historyData'
      // if (this.coinList.length) {
      //   return 'historyData'
      // }
      // if (!this.historyList.length) {
      //   return 'noIcon historyData'
      // }
      return 'historyData';
    },
  },
  created() {
    this.dataReset();
  },
  mounted() {
    // 获取搜索历史记录
    const historyData = localStorage.getItem('historyDatas');
    this.historyList = historyData ? JSON.parse(historyData) : [];
    this.codeListData = this.$store.state.app.codeList.list;
  },
  beforeDestroy() {},
  methods: {
    dataReset() {
      // 币种列表
      this.coinList = [{
        coinId: '',
        code: this.$t('order.all')
      }];
      // 排序时间
      this.typeList = [{
        value: '',
        label: this.$t('order.all')
      }, {
        value: 1,
        label: this.$t('order.buy')
      }, {
        value: 2,
        label: this.$t('order.sell')
      }];
      // 订单时间
      this.historyTypeList = [
        {
          value: 0,
          label: this.$t('order.nearlyOrder'), // 近3个月
        },
        {
          value: 3,
          label: this.$t('order.order2020'), // 2019年
        },
        {
          value: 2,
          label: this.$t('order.order2019'), // 2019年
        },
        {
          value: 1,
          label: this.$t('order.order2018'), // 2018年
        },
      ];
      if (this.$appName === 'tronNewdex') {
        this.historyTypeList = this.historyTypeList.filter(v => v.value !== 1)
      }
      // 方向列表
      this.coinType = {
        EOS: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'EOS',
            label: 'EOS',
          },
          {
            value: 'EUSD',
            label: 'EUSD',
          },
          {
            value: 'CUSD',
            label: 'CUSD',
          }
        ],
        BOS: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'BOS',
            label: 'BOS',
          }
        ],
        MEETONE: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'MEETONE',
            label: 'MEETONE',
          }
        ],
        ENU: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'ENU',
            label: 'ENU',
          }
        ],
        FIBOS: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'FIBOS',
            label: 'FIBOS',
          }
        ],
        TELOS: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'TELOS',
            label: 'TELOS',
          }
        ],
        WAX: [
          {
            value: 0,
            label: null,
          },
          {
            value: 'WAX',
            label: 'WAX',
          }
        ],
        // LYNX: [
        //   {
        //     value: 0,
        //     label: null,
        //   },
        //   {
        //     value: 'LYNX',
        //     label: 'LYNX',
        //   }
        // ]

      };
      // 成交状态
      this.statusTip = [
        this.$t('order.noDeal'),
        this.$t('order.partDeal'),
        this.$t('order.allDeal'),
      ];
    },
    // 订单导出 -- 询问
    handleExportOrder() {
      if (this.hasDataForTable === 0) {
        this.$message.warning(this.$t('order.noOrderExport'));
        return;
      }
      this.$confirm(this.$t('order.limitOrder'), this.$t('public.reTip'), {
        confirmButtonText: this.$t('public.sure'),
        cancelButtonText: this.$t('public.cancel'),
        center: true,
      }).then(() => {
        // 订单导出 -- 授权
        const token = localStorage.getItem('Frontend-Token');
        if (token) {
          // 判断订单导出次数
          this.handleJudgeExportNum((res) => {
            if (res !== 'error') {
              if (res === 0) {
                this.$message.error(this.$t('order.pleaseTryAgain'));
                return;
              }
              this.handleExportOrderAction();
            }
          });
          return;
        }
        this.handleAuthorized(() => {
          this.handleJudgeExportNum((res) => {
            if (res !== 'error') {
              if (res === 0) {
                this.$message.error(this.$t('order.pleaseTryAgain'));
                return;
              }
              this.handleExportOrderAction();
            }
          });
        });
      }).catch(() => {});
    },
    // 订单导出 -- 执行导出操作
    handleExportOrderAction() {
      this.$http.post('/order/exportHistoryOrder', this.formData, {
        responseType: 'blob',
        // headers: {
        //   'Content-Type': 'application/json',
        // }
      }).then((res) => {
        this.$message.success(this.$t('order.exportSuccess'));
        const date = this.formData;
        const beginDate = date.beginDate; // 开始时间
        const endDate = date.endDate; // 结束时间
        const blob = new Blob([res]);
        const fileName = `Newdex - ${this.$t('ndxStake.orderExport')}(${beginDate} - ${endDate}).xls`;
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      });
    },
    // 判断导出次数剩余
    handleJudgeExportNum(callback) {
      this.$http.post('/order/getRemainExportCount').then((res) => {
        if (res.code !== 0) {
          this.$message.error(this.$t('order.exportError'));
          callback('error');
          return;
        }
        callback(res.remainExportCount);
      });
    },
    // 监听子组件传递过来的日期范围
    ListenTimeArr(childTimeArr) {
      const val = childTimeArr;
      const istrue = val && val.length > 0;
      this.formData.beginDate = istrue ? val[0] : ''; // 开始时间
      this.formData.endDate = istrue ? val[1] : ''; // 结束时间
      this.handleSearchData();
    },
    // 搜索值，传递
    handleSearchData() {
      this.$emit('ListenSearchHead', 'form', this.formData)
    },

    // 授权操作
    handleAuthorized(callback) {
      authorized(this, (code, result) => {
        if (code === 'error') { // 授权错误
          console.log(result); // eslint-disable-line
          return;
        }
        callback();
      });
    },
    // 选择历史记录
    handleSelectHistory(item, index) {
      if (this.isClick) {
        this.historyVisible = false;
        this.$refs.historyInput.blur();
        this.formData.coinCode = item;
        this.historyList.splice(index, 1);
        this.historyList.unshift(item);
        localStorage.setItem('historyDatas', JSON.stringify(this.historyList));
        const itemId = this.codeListData.find(v => v.symbolFormat === item).id;
        this.formData.symbolId = itemId;
        const items = {
          id: itemId,
          symbol: item
        };
        this.codeList = [items];
        this.handleSearchData();
        this.isClick = false;
        setTimeout(() => {
          this.isClick = true;
        }, 200);
      }
    },
    // 显示币种列表
    handleShowCodeList() {
      // if (!this.formData.coinCode) return;
      if (!this.formData.coinCode) {
        this.formData.symbolId = '';
        this.handleSearchData();
        return;
      }
      this.codeList = this.codeListData.filter(v => v.symbolFormat.indexOf(this.formData.coinCode.toUpperCase()) > -1);
      if (!this.codeList.length) {
        this.historyVisible = false;
      } else {
        this.historyVisible = true;
      }
    },
    // 选择币种列表
    handleSelectCodeList(item) {
      this.historyVisible = false;
      this.formData.coinCode = item.symbolFormat;
      this.formData.symbolId = item.id;
      this.historyList.unshift(item.symbolFormat);
      this.historyList = Array.from(new Set(this.historyList));
      this.codeList = [item];
      if (this.historyList.length > 6) {
        this.historyList.pop();
      }
      localStorage.setItem('historyDatas', JSON.stringify(this.historyList));
      this.handleSearchData();
    },
    // 重置搜索
    handleInitSearch() {
      this.formData.symbolId = '';
      // this.formData.coinCode = '';
      // this.$refs.historyInput.blur();
      // this.historyVisible = false;
      this.handleSearchData();
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/variables.scss';

.searchHead {
  .tools{
    text-align: left;
    color: #999;
    font-size: 12px;
    padding: 20px 20px 8px;
    background: #fff;

    /deep/ .el-checkbox__label {
      font-size: 12px;
    }

    /deep/ .el-button--primary.is-plain,
    /deep/ .el-button--primary.is-plain:focus{
      background: transparent;
      border: 1px solid #dcdfe6;
      color: #333;
    }

    /deep/ .el-button--primary.is-plain:hover{
      background: #278EDA;
      color: white;
    }
    .item{
      position: relative;
      display: inline-block;
      // padding-left: 31px;
      padding-left: 10px;
      // .dataList {
      //   position: absolute;
      //   top: 0;
      //   right: 0;
      // }
    }
    .export {
      cursor: pointer;
      line-height: 40px;
      margin-left: 10px;
      margin-right: 20px;
      span {
        color: #278EDA;
      }
    }
    .coinType {
      padding-left: 10px !important;
      /deep/ .el-input__inner {
      }
    }
    .item:nth-child(1){
      // padding-left: 36px;
      padding-left: 10px;
    }
    .item:nth-child(3), .item:nth-child(4), .item:nth-child(5){
      padding-left: 15px;
    }
    .item:nth-child(6),
    .item:last-child {
      // float: right;
      margin-right: 10px;
      // padding-left: 0;
    }
    .selectWidth{
      width: 130px;
    }

    /deep/ .el-range-separator{
      width: auto;
    }

    .icon-daochu {
      display: inline-block;
      vertical-align: middle;
      margin-top: -4px;
    }

    .label{
      line-height: 40px;
      margin-right: 10px;

      .icon-eos{
        margin-right: 10px;
      }
    }
  }
}

.volatility {
  cursor: pointer;
  i {
    display: inline-block;
    vertical-align: middle;
    font-size: 15px;
    margin: -2px 5px 0 0;
  }
}

.theme-1B1D27 {
  .tools{
    background: $-black1;

    /deep/ .el-button--primary.is-plain,
    /deep/ .el-button--primary.is-plain:focus{
      border: 1px solid #4e5b85;
      color: rgba(255,255,255,0.8);
      box-shadow: 0px 0px 0px;
    }
  }
}
</style>
